package cn.cnhis.online.base;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.ButterKnife;
import cn.cnhis.online.activity.login.contract.ILoginContract;


public abstract class BaseMvpActivity<V extends IView, P extends IPresenter<V>> extends BaseActivity<IView, IPresenter<ILoginContract.View>> implements MvpCallback<V, P> {


    protected P mPresenter;
    protected V mView;
    protected JsonParser mJp;
    protected Gson mGson;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        inited();
    }

    public JsonParser getJsonParser() {
        return mJp;
    }

    public Gson getGson() {
        return mGson;
    }

    /**
     * 将JavaBean序列化为JSON文本
     *
     * @param object
     * @return
     */
    public static JSONObject toJSONObject(Map object) {
        return new JSONObject(object);
    }

    public static JSONObject toJSONObject(String object) {
        try {
            if (object == null)
                return null;
            return new JSONObject(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (isFinishing()) {
            setMvpView(null);
            setPresenter(null);
        }
    }

    /**
     * 注意如果在这里获取intent的数据在构造中传给Presenter的话,获取代码需要在super调用之前
     */
    @CallSuper
    protected void init() {
        mJp = new JsonParser();
        mGson = new Gson();
        mView = createView();
        if (getPresenter() == null) {
            mPresenter = createPresenter();
            if (mPresenter != null) {
                getLifecycle().addObserver(mPresenter);
            }
        }
    }

    @Override
    public P getPresenter() {
        return mPresenter;
    }

    @Override
    public void setPresenter(P presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public V getMvpView() {
        return this.mView;
    }

    @Override
    public void setMvpView(V view) {
        this.mView = view;
    }

    public Context getContext() {
        return this;
    }

    @CallSuper
    @Override
    public void inited() {
        ButterKnife.bind(this);
        mPresenter.attachView(getMvpView());
    }

    public void setResultAndFinish(int result) {
        setResult(result);
        finish();
    }
}
